<?php

class Admin_settings extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url', 'date'));
        $this->load->library(array('session', "table", "pagination", 'form_validation'));

        if ($this->session->userdata("admin") === false) {
            redirect("admin/index/You must login first");
        }


        $this->load->model("settings/admins_model", "", TRUE);
        $this->load->model("settings/clients_model", "", TRUE);
        $this->load->model("settings/sbus_model", "", TRUE);
        $this->load->model("settings/service_types_model", "", TRUE);
        $this->load->model("settings/departments_model", "", TRUE);
        $this->load->model("settings/org_types_model", "", TRUE);
        $this->load->model("settings/bus_types_model", "", TRUE);
        $this->load->model("settings/document_types_model", "", TRUE);
        $this->load->model("consolidate_model", "", TRUE);
        $this->load->model("settings/kim_model", "", TRUE);
        $this->load->model("settings/log_model", "", TRUE);
        $this->load->model("settings/tabs_model", "", TRUE);
        $this->load->model("settings/tab_cats_model", "", TRUE);
        $this->load->model("settings/groups_model", "", TRUE);
        $this->load->model("settings/contact_model", "", TRUE);

        $this->indexes = array();
        $this->indexes["kim"] = 0;
        $this->indexes["clients"] = 1;
        $this->indexes["sbus"] = 2;
        $this->indexes["service_types"] = 3;
        $this->indexes["org_types"] = 4;
        $this->indexes["bus_types"] = 5;
        $this->indexes["admins"] = 6;
        $this->indexes["docType"] = 7;
        $this->indexes["tabs"] = 9;
        $this->indexes["tab_cats"] = 10;

        $this->template = array(
            'table_open' => '<table style=\'border:5px;border-style:solid;width: 100%;\'>',
            'heading_row_start' => '<tr style=\'background-color:#ccccff;text-transform:capitalize\'>',
            'row_start' => '<tr style="background-color:#eeefff;">',
            'row_alt_start' => '<tr style="background-color:#deefff;">'
        );
        $this->table->set_template($this->template);
        $this->myConfig['uri_segment'] = 2;
        $this->myConfig['per_page'] = '50';

        $this->const['hits'] = $this->kim_model->getHitCount();

        $this->access_menus = array("admins" => "Users", "groups" => "Groups");
    }

    function index($tab=0, $message="") {
        $data["title"] = "- Settings";
        $data["cats"] = $this->tab_cats_model->getAll();
        $data["wide"] = TRUE;
        $this->load->view('templates/header', $data);
        $data['tab'] = $tab;
        $data['message'] = urldecode($message);
        $this->load->view('admin/settings', $data);
        $this->load->view('templates/footer', $this->const);
    }

    function kim() {
        $row = $this->kim_model->getAll();
        if (count($row) == 0) {
            $row['errors'] = TRUE;
        }
        $this->load->view("admin/settings/kim", $row);
    }

    function kimEdit() {
        $row = $this->kim_model->getAll(FALSE);
        if (count($row) == 0) {
            $row['errors'] = TRUE;
        }
        $this->load->view("admin/settings/kim_edit", $row);
    }

    function kimSave() {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'pdf|doc|docx';
        $config['max_size'] = '5000';
        $this->load->library('upload', $config);
        $kim_council = NULL;
        $board_of_fellows = NULL;
        $kim_comitees = NULL;

        if ($this->upload->do_upload("kim_council")) {
            $data = $this->upload->data();
            $kim_council = $data['file_name'];
        }
        if ($this->upload->do_upload("board_of_fellows")) {
            $data = $this->upload->data();
            $board_of_fellows = $data['file_name'];
        }
        if ($this->upload->do_upload("kim_comitees")) {
            $data = $this->upload->data();
            $kim_comitees = $data['file_name'];
        }
        $this->kim_model->update($this->session->userdata("username"), $kim_council, $board_of_fellows, $kim_comitees);
        redirect("admin_settings/index/" . $this->indexes["kim"] . "/KIM details updated");
    }

    function admins($message="") {
        $data['message'] = urldecode($message);
        $query = $this->admins_model->getAll();
        $this->myConfig['total_rows'] = count($query);
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/admins";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('Added by', 'Username', 'Names', 'Position', "Date registered", "Last Login", 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $data['access_menus'] = $this->access_menus;
        $data['title'] = "Users";
        $this->load->view("admin/settings/admins", $data);
    }

    function groups($message="") {
        $data['message'] = urldecode($message);
        $query = $this->groups_model->getAll();
        $this->table->set_heading(array('Added by', 'Name', 'Description', 'Modified', 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $data['pagina'] = "";
        $data['access_menus'] = $this->access_menus;
        $data['title'] = "Groups";
        $this->load->view("admin/settings/groups", $data);
    }

    function groupPermissions($tid, $offset=0) {
        $this->myConfig['per_page'] = 15;
        $query = $this->groups_model->permisions($tid, $offset, $this->myConfig['per_page']);
        $this->myConfig['uri_segment'] = 4;
        $this->myConfig['total_rows'] = $this->groups_model->size();
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/groupPermissions/$tid";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('', 'Tab', 'Read', 'Write', 'Update', 'Delete')); //,
        $data['tablet'] = $this->table->generate($query);
//        $data['rawAccess'] = $query;
        $data['access_menus'] = $this->access_menus;
        $data['access_menus']["groupPermissions/$tid"] = "Permissions";
        $data['title'] = "Groups";
        $this->load->view("admin/settings/groups", $data);
    }

    function setAccess($groupId, $tabId, $access) {
        $this->groups_model->setAccess($groupId, $tabId, $access);
    }

    function saveGroup() {
        $this->form_validation->set_rules('name', 'Group name', 'required');
        if ($this->form_validation->run() == FALSE) {
            echo validation_errors();
        } else {
            $this->groups_model->newGroup($this->session->userdata("username"));
        }
    }

    function deleteGroup($tid) {
        $this->groups_model->delete($tid);
        echo "Deleted $tid";
    }

    function saveAdmin() {
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|matches[password2]|md5');
        $this->form_validation->set_rules('password2', 'Password Confirmation', 'required');
        $this->form_validation->set_rules('names', 'Names', 'required');
        $this->form_validation->set_rules('position', 'Position', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["admins"] . "/" . strip_tags(str_replace(".", " ", str_replace("\n", " ", validation_errors()))));
        } else {
            $this->admins_model->newAdmin($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["admins"] . "/Admin saved");
        }
    }

    function deleteAdmin($tid) {
        $this->admins_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["admins"] . "/Record deleted");
    }

    function tabs($cat=NULL, $message="") {
        if ($cat == "0") {
            $cat = NULL;
        }
        $data['message'] = urldecode($message);
        $query = $this->tabs_model->getAll(TRUE, $cat);
        $this->myConfig['total_rows'] = count($query);
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/tabs";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('Added by', 'Name', 'URL', "Active", 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $catsQuery = $this->tab_cats_model->getAll();
        $data['cats'] = $catsQuery;
        $data['currentCat'] = $cat == NULL ? 0 : $cat;
        $this->table->set_heading(array('Id', 'Name', 'Links'));
        $data['tab_cats'] = $this->table->generate($catsQuery);
        $this->load->view("admin/settings/tabs", $data);
    }

    function saveTab() {
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('url', 'URL', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["tabs"] . "/" . strip_tags(str_replace(".", " ", str_replace("\n", " ", validation_errors()))));
        } else {
            $this->tabs_model->newTab($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Tabs saved");
        }
    }

    function updateTab($tid, $cat) {
        $this->tabs_model->update($tid, $cat);
        redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Tabs updated");
    }

    function changeTabOrder($tid, $direction) {
        $this->tabs_model->changeOrder($tid, $direction);
        redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Tabs order updated");
    }

    function sortTabs() {
        $this->tabs_model->rearrangeOrder(TRUE);
        redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Tabs sorted");
    }

    function activateTab($tid) {
        $this->tabs_model->activate($tid);
        redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Tabs activated/deactivated");
    }

    function deleteTab($tid) {
        $this->tabs_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Record deleted");
    }

    function saveTabCat() {
        $this->form_validation->set_rules('name', 'Name', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["tabs"] . "/" . strip_tags(str_replace(".", " ", str_replace("\n", " ", validation_errors()))));
        } else {
            $this->tab_cats_model->newTabCat($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Tab Cat saved");
        }
    }

    function deleteTabCat($tid) {
        $this->tab_cats_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["tabs"] . "/Record deleted");
    }

    function clients($message="") {
        $data['message'] = urldecode($message);
        $query = $this->clients_model->getAll();
        $data['yeses'] = $this->consolidate_model->getYeses();
        $this->myConfig['total_rows'] = count($query);
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/clients";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('Added by', 'Client name', 'Link', 'VAT Compliant', 'List of Directors', 'Date', 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $this->load->view("admin/settings/clients", $data);
    }

    function saveClient() {
        $this->form_validation->set_rules('name', 'Name', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["clients"] . "/" . strip_tags(str_replace("\n", " ", validation_errors())));
        } else {
            $this->clients_model->newClient($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["clients"] . "/Details saved");
        }
    }

    function deleteClient($tid) {
        $this->clients_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["clients"] . "/Record deleted");
    }

    function sbus($message="") {
        $data['message'] = urldecode($message);
        $query = $this->sbus_model->getAll();
        $this->myConfig['total_rows'] = count($query);
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/sbus";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('Added by', 'SBU', 'Date', 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $this->load->view("admin/settings/sbus", $data);
    }

    function saveSbu() {
        $this->form_validation->set_rules('name', 'Name', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["sbus"] . "/" . strip_tags(str_replace("\n", " ", validation_errors())));
        } else {
            $this->sbus_model->newSbu($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["sbus"] . "/Details saved");
        }
    }

    function deleteSbu($tid) {
        $this->sbus_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["sbus"] . "/Record deleted");
    }

    function docTypes($message="") {
        $data['message'] = urldecode($message);
        $query = $this->document_types_model->getAll("0");
        $htmlstr = "<a href='javascript:addDocType(0)'>Add category</a> ";
        $htmlstr .= "<ol type='1'>";
        foreach ($query as $row) {
            $htmlstr.="<li>" . $row['name'] . " <a href='javascript:addDocType(" . $row['tid'] . ")'>Add subcategory</a>
                <a href='javascript:editDocType(" . $row['tid'] . ",\"" . $row['name'] . "\")'>Edit</a>
                    <a href='javascript:gotoUrl(\"" . base_url() . "index.php?/admin_settings/deleteDocType/" . $row['tid'] . "\",\"Are you sure to delete this document type?\")'>Delete</a>
                <a href='javascript:loadUrl(\"#doc_type_result\",\"" . base_url() . "index.php?/admin_settings/docInfo/" . $row['tid'] . "\")'>info</a></li>";
            $subquery = $this->document_types_model->getAll($row['tid']);
            $htmlstr.= "<ol type='i'>";
            foreach ($subquery as $subrow) {
                $htmlstr.="<li>" . $subrow['name'] . "
                <a href='javascript:editDocType(" . $subrow['tid'] . ",\"" . $subrow['name'] . "\")'>Edit</a>
                    <a href='javascript:gotoUrl(\"" . base_url() . "index.php?/admin_settings/deleteDocType/" . $subrow['tid'] . "\",\"Are you sure to delete this document type?\")'>Delete</a>
                <a href='javascript:loadUrl(\"#doc_type_result\",\"" . base_url() . "index.php?/admin_settings/docInfo/" . $subrow['tid'] . "\")'>info</a></li>";
            }
            $htmlstr.= "</ol>";
        }
        $htmlstr.= "</ol>";
        $data['tablet'] = $htmlstr;
        $this->load->view("admin/settings/document_types", $data);
    }

    function docInfo($tid, $div) {
        $row = $this->document_types_model->getAll(NULL, $tid);
        if (count($row) == 0) {
            $row['errors'] = TRUE;
        } else {
            $row = $row[0];
        }
        $row['div'] = $div;
        $this->load->view("admin/settings/docTypeInfo", $row);
    }

    function saveDocType($parent, $name) {
        $this->document_types_model->newDocType($this->session->userdata("username"), $parent, $name);
        redirect("admin_settings/index/" . $this->indexes["docType"] . "/Details saved");
    }

    function editDocType($tid, $newName) {
        $this->document_types_model->updateDocType($tid, $newName);
        redirect("admin_settings/index/" . $this->indexes["docType"] . "/Details updated");
    }

    function deleteDocType($tid) {
        $this->document_types_model->deleteDocType($tid);
        redirect("admin_settings/index/" . $this->indexes["docType"] . "/Record deleted");
    }

    function service_types($message="") {
        $data['message'] = urldecode($message);
        $query = $this->service_types_model->getAll();
        $this->myConfig['total_rows'] = count($query);
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/service_types";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('Added by', 'Service type', 'Date', 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $this->load->view("admin/settings/service_types", $data);
    }

    function saveService_type() {
        $this->form_validation->set_rules('name', 'Name', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["service_types"] . "/" . strip_tags(str_replace("\n", " ", validation_errors())));
        } else {
            $this->service_types_model->newService_type($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["service_types"] . "/Details saved");
        }
    }

    function deleteServiceType($tid) {
        $this->service_types_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["service_types"] . "/Record deleted");
    }


    function org_types($message="") {
        $data['message'] = urldecode($message);
        $query = $this->org_types_model->getAll();
        $this->myConfig['total_rows'] = count($query);
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/org_types";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('Added by', 'Organization', 'Date', 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $this->load->view("admin/settings/org_types", $data);
    }

    function saveOrg_type() {
        $this->form_validation->set_rules('name', 'Name', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["org_types"] . "/" . strip_tags(str_replace("\n", " ", validation_errors())));
        } else {
            $this->org_types_model->newOrg_type($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["org_types"] . "/Details saved");
        }
    }

    function deleteOrgType($tid) {
        $this->org_types_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["org_types"] . "/Record deleted");
    }

    function bus_types($message="") {
        $data['message'] = urldecode($message);
        $query = $this->bus_types_model->getAll();
        $this->myConfig['total_rows'] = count($query);
        $this->myConfig['base_url'] = base_url() . "index.php?/admin_settings/bus_types";
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('Added by', 'Business type', 'Date', 'Links'));
        $data['tablet'] = $this->table->generate($query);
        $this->load->view("admin/settings/bus_types", $data);
    }

    function saveBus_type() {
        $this->form_validation->set_rules('name', 'Business type', 'required');
        if ($this->form_validation->run() == FALSE) {
            redirect("admin_settings/index/" . $this->indexes["bus_types"] . "/" . strip_tags(str_replace("\n", " ", validation_errors())));
        } else {
            $this->bus_types_model->newBus_type($this->session->userdata("username"));
            redirect("admin_settings/index/" . $this->indexes["bus_types"] . "/Details saved");
        }
    }

    function deleteBusinessType($tid) {
        $this->bus_types_model->delete($tid);
        redirect("admin_settings/index/" . $this->indexes["bus_types"] . "/Record deleted");
    }

    function log($field=NULL, $search=NULL, $offset=NULL) {
        if ($search) {
            $this->myConfig['uri_segment'] = 5;
            $this->myConfig['base_url'] = base_url() . "index.php?/mis/log/$field/$search";
        } else {
            if ($field) {
                $offset = $field;
            } else {
                $offset = 0;
            }
            $this->myConfig['base_url'] = base_url() . "index.php?/mis/log";
        }
        $query = $this->log_model->adminGetAll($field, $search, $offset, $this->myConfig['per_page']);
        $countQuery = $this->log_model->adminGetAll($field, $search);
        $this->myConfig['total_rows'] = count($countQuery);
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('', 'Action', "Type", 'Decsription', 'User', 'Date'));
        $data['tablet'] = $this->table->generate($query);
        $this->load->view("admin/settings/log", $data);
    }
    
    
    function contact_message($field=NULL, $search=NULL, $offset=NULL) {
        if ($search) {
            $this->myConfig['uri_segment'] = 5;
            $this->myConfig['base_url'] = base_url() . "index.php?/mis/contact_message/$field/$search";
        } else {
            if ($field) {
                $offset = $field;
            } else {
                $offset = 0;
            }
            $this->myConfig['base_url'] = base_url() . "index.php?/mis/contact_message";
        }
        $query = $this->contact_model->getAll($field, $search, $offset, $this->myConfig['per_page']);
        $countQuery = $this->contact_model->getAll($field, $search);
        $this->myConfig['total_rows'] = count($countQuery);
        $this->pagination->initialize($this->myConfig);
        $data['pagina'] = $this->pagination->create_links();
        $this->table->set_heading(array('', 'Email', "Subject", 'Decsription', 'Date', 'Read'));
        $data['tablet'] = $this->table->generate($query);
        $this->load->view("admin/settings/contact_messages", $data);
    }

}

?>
